package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojo.ApUserSearch;
import com.heima.search.pojo.HistorySearchDto;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.thread.ApUserThreadUtil;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Author: JW
 * @Description: TODO
 * @DateTime: 2022-02-18 15:03
 **/
@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * @param searchWords 词条
     * @param id 用户id
     * @Author: JW
     * @Description: TODO 保存 && 修改 搜索词条
     * @Date: 15:20 2022-02-18
     * @Param: [searchWords, id]
     * @return: void
     */
    @Override
    @Async
    public void save(String searchWords, Integer id) {

        //查询出是否含有该词条
        ApUserSearch odlApUserSearch = mongoTemplate.findOne(Query
                .query(Criteria.where("userId").is(id).and("keyword").is(searchWords)), ApUserSearch.class);

        //如果有 直接修改查询时间 并直接返回
        if (odlApUserSearch != null){

            //修改最新时间 保存
            odlApUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(odlApUserSearch);

            return;
        }

        //如果没有，就查询所有搜索 并按照时间升序
        List<ApUserSearch> userSearchList = mongoTemplate.find(Query.query(Criteria
                .where("userId").is(id)).with(Sort.by(Sort.Order.by("createdTime"))),ApUserSearch.class);

        //构造对象
        ApUserSearch apUserSearch = new ApUserSearch();

        apUserSearch.setUserId(id);
        apUserSearch.setKeyword(searchWords);
        apUserSearch.setCreatedTime(new Date());

        //小于10条就保存
        if (userSearchList.size() < 10){

            mongoTemplate.save(apUserSearch);
        }else {
            //此时搜索词条已到达10条 就替换最后时间搜索

            //拿到最后一条 并删除
            ApUserSearch odlapUserSearch = userSearchList.get(0);
            mongoTemplate.remove(odlapUserSearch);

            //保存最新的
            mongoTemplate.save(apUserSearch);
        }

    }

    /**
     * @Author: JW
     * @Description: TODO 查询所有搜索词条
     * @Date: 15:49 2022-02-18
     * @Param: []
     * @return: com.heima.model.common.dtos.ResponseResult
     **/
    @Override
    public ResponseResult findHistory() {

        ApUser apUser = ApUserThreadUtil.getUser();

        if (apUser == null || apUser.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        List<ApUserSearch> userSearchList = mongoTemplate.find(Query.query(Criteria
                .where("userId").is(apUser.getId())).with(Sort.by(Sort.Order.desc("createdTime"))),ApUserSearch.class);

        return ResponseResult.okResult(userSearchList);
    }

    /**
     * @param historySearchDto
     * @Author: JW
     * @Description: TODO 删除历史搜索
     * @Date: 15:57 2022-02-18
     * @Param: [historySearchDto]
     * @return: com.heima.model.common.dtos.ResponseResult
     */
    @Override
    public ResponseResult remove(HistorySearchDto historySearchDto) {

        ObjectId id = new ObjectId(historySearchDto.getId());

        mongoTemplate.remove(Query.query(Criteria.where("id").is(id)),ApUserSearch.class);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
